package demo1;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-04-07
 * Time: 19:14
 */
public class HistEqualize {
    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    /**
     * 彩色直方图均衡
     * @param src
     * @return
     */
    public static Mat histEqualize(Mat src) {
        Mat dst = src.clone();
        Imgproc.cvtColor(dst, dst, Imgproc.COLOR_BGR2YCrCb);//brg -> ycrcb

//        HighGui.imshow("oip",dst);
//        HighGui.waitKey(0);

        List<Mat> list1 = new ArrayList<>();
        Core.split(dst, list1);//分解通道
        Imgproc.equalizeHist(list1.get(0), list1.get(0));//均衡化
//        Imgproc.equalizeHist(list1.get(1), list1.get(1));
//        Imgproc.equalizeHist(list1.get(2), list1.get(2));

//        HighGui.imshow("oip",list1.get(0));
//        HighGui.waitKey(0);

        Core.normalize(list1.get(0), list1.get(0), 0, 255, Core.NORM_MINMAX);
//        Core.normalize(list1.get(1), list1.get(1), 0, 255, Core.NORM_MINMAX);
//        Core.normalize(list1.get(2), list1.get(2), 0, 255, Core.NORM_MINMAX);
        Core.merge(list1, dst);//合并通道

//        HighGui.imshow("oip",dst);
//        HighGui.waitKey(0);

        Imgproc.cvtColor(dst, dst, Imgproc.COLOR_YCrCb2BGR);//ycrcb -> bgr
        return dst;
    }


    public static void main(String[] args) {
        Mat src = Imgcodecs.imread("src2.png");
        HighGui.imshow("src", src);
        HighGui.waitKey();

        Mat dst = histEqualize(src);

        HighGui.imshow("dst", dst);
        HighGui.waitKey();
    }

    /**
     * 灰度图直方图均衡
     * @param args
     */
    public static void main1(String[] args) {
        Mat src = Imgcodecs.imread("src2.png", Imgcodecs.IMREAD_GRAYSCALE);
        HighGui.imshow("src", src);
        HighGui.waitKey();

        Mat dst = new Mat();
        Imgproc.equalizeHist(src, dst);
        HighGui.imshow("dst", dst);
        HighGui.waitKey();

    }
}
